<template>
  <div class="box"
       id='water-bal-meal'>
    <Row>
      <Col :xs="24"
           :sm="24"
           :md="24"
           :lg="24"
           class="Col_right">
      <div class="Col_right_list"
           v-if="true">
        <Row type='flex'
             justify='end'
             style='padding:20px'>
          <Col><Button type="primary"
                  @click="add"
                  style="width:80px;">添加</Button></Col>
        </Row>
        <Table :columns="columns7" :height="this.tableHeight"
               class="table-list"
               :data="data6">
          <template slot-scope="{ row }"
                    slot="status">
            <span>{{ row.status }}</span>
          </template>
          <template slot-scope="{ row }"
                    slot="newName">
            <span>{{ row.newName }}</span>
          </template>
          <template slot-scope="{ row, index }"
                    slot="action">
            <Icon class="iconsys iconedit"
                  title="编辑"
                  @click="uptShow(row)" />
            <Poptip confirm
                    title="你确定要删除吗？"
                    style="text-align:left"
                    class="poptip_del"
                    @on-ok="remove(row,index)"
                    @on-cancel="cancel">
              <Icon class="iconsys icondel"
                    title="删除" />
            </Poptip>
          </template>
        </Table>
        <div class="content_page">
          <span>共计{{formValidate.totalCount}}条</span>
          <Page :total="formValidate.totalCount"
                @on-change="pageNum"
                @on-page-size-change="page_size"
                class-name="page"
                :page-size="listpage.limit"
                :current="listpage.offset"
                ref="pages"
                show-sizer />
        </div>
      </div>
      </Col>
    </Row>

    <Drawer :title="title"
            :transfer='false'
            width="540"
            :closable="false"
            v-model="value5">
      <Form ref="formValidate"
            :model="formValidate"
            :rules="ruleValidate"
            :label-width="100"
            style="padding:20px 0 20px 40px">
        <FormItem label="水吧套餐名称:"
                  prop="name">
          <Input v-model="formValidate.name"
                 @on-keyup="keyupname"
                 :maxlength="14"
                 placeholder="最多输入14字"
                 style="width:280px"></Input>
        </FormItem>
        <FormItem label="现金购买:"
                  prop="cash">
          <Input v-model="formValidate.cash"
                 :maxlength="7"
                 @on-blur="priceBlur"
                 @on-keyup="changeprice"
                 placeholder="输入范围为0.00~9999.99"
                 style="width:280px"></Input>
          <span style="margin-left:8px">元</span>
        </FormItem>
        <FormItem label="游戏币购买:"
                  prop="game">
          <Input v-model="formValidate.game"
                 @on-keyup="changecoinNum"
                 @on-blur="changegame"
                 :maxlength="6"
                 placeholder="输入范围为1~999999"
                 style="width:280px"></Input>
          <span style="margin-left:8px">枚</span>
        </FormItem>
        <FormItem label="是否启用:"
                  prop="gender"
                  style="width:280px">
          <RadioGroup v-model="formValidate.gender"
                      @on-change="Radio_change">
            <Radio label="1"
                   style="margin-right:60px">是</Radio>
            <Radio label="0">否</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="上传图片:"
                  prop="imgUrl"
                  class="set_ct_form_up">
          <Upload ref="upload"
                  :format="['jpg','png']"
                  :max-size="100"
                  :on-success="handleSuccess"
                  :on-format-error="handleFormatError"
                  :on-exceeded-size="handleMaxSize"
                  type="drag"
                  :show-upload-list="false"
                  :action="$config.uploadImg"
                  style="display: inline-block;width:96px;">
            <img :src="formValidate.imgUrl?formValidate.imgUrl:defaultUrl"
                 style="display: inline-block;width:96px;height:96px;vertical-align: top;"
                 alt="">
            <p v-if="formValidate.imgUrl"
               class="replace_tit">更换</p>
          </Upload>
          <div style="width:132px;height:72px;line-height:18px;color: #464C5B;margin-left:24px;">支持格式：.jpg、.png；规格：235*110；大小：≤100K</div>
        </FormItem>
        <FormItem label="添加商品："
                  prop="productList"
                  style="width:280px">
          <Button type="primary"
                  @click="value6 = true"
                  style="width:80px">添加</Button>
          <p style="color:#ed4014"
             v-show='this.formValidate.productList.length<1 && isShow'>请选择商品</p>
          <div style="margin-top:10px;width:280px">
            <ul>
              <li v-for="(item, index) in this.formValidate.productList"
                  :key="index"
                  style="display:block;margin-bottom:10px">
                <span style="border:1px solid #dcdee2;border-radius:3px;padding:10px 0">
                  <span class="name"
                        style="padding:0 8px">名称:{{item.title}}</span>
                  <span class="grid_btn"
                        @click="cancelSelected(item, index)">×</span>
                </span>
              </li>
            </ul>
          </div>
        </FormItem>
      </Form>
      <div class="demo-drawer-footer1 footer1">
        <Button @click="handleReset('formValidate')"
                style="margin-right: 20px;width:72px">取消</Button>
        <Button type="primary"
                :disabled='isDisabled'
                @click="handleSubmit('formValidate')"
                style="width:72px">确认</Button>
      </div>
    </Drawer>

    <Drawer title="添加商品"
            :closable="false"
            v-model="value6"
            width="360"
            :transfer='false'>
      <div class="Drawer_Tree">
        <Input search
               placeholder="请输入"
               @on-search="sousuo"
               enter-button
               @on-keyup="changeName"
               v-model="formValidate.sousuo"
               @on-change="sousuo_change" />
        <Tree v-show="showSousuo"
              :data="data3"
              :load-data="loadData"
              :render="renderContent"
              ref="tree"></Tree>
        <div v-if="!showSousuo">
          <ul style="margin-top:10px"
              v-if="sousuoList.length>0">
            <li :class="[ item.Sousuoclass ? 'sosuoli_after' : 'sosuoli_befor' ]"
                @click="sousuoclickli(item,item.productId,index)"
                ref="sousuoli"
                style='list-style:none;display:flex'
                v-for="(item, index) in sousuoList"
                :data-id="item.productId"
                :key="index">
              <p style="margin-left:10px;width:240px">
                {{item.productName}}
              </p>
              <Icon type="md-checkmark"
                    :class="[ Iconclass ? 'Icon_after' : 'Icon_befor' ]"
                    ref="Iconclass" />
            </li>
          </ul>
          <div v-if="sousuoList.length === 0"
               style="margin-top:25px">没有搜索到 "{{this.formValidate.sousuo}}" 的商品</div>
        </div>
      </div>
      <div class="demo-drawer-footer1 footer2">
        <Button type="default"
                @click="cancelSelect"
                style="width:72px">取消</Button>
        <Badge :count="num"
               style="margin:0 20px 0 20px">
          <Button type="default"
                  @click="yes"
                  style="width:72px">已选商品</Button>
        </Badge>
        <Button type="primary"
                @click="add_no"
                style="width:72px">确认</Button>
      </div>
    </Drawer>
    <Drawer title="已选商品"
            :closable="false"
            v-model="value7"
            class-name="Drawer_three"
            :transfer='false'
            width="360">
      <Button type="primary"
              class="qingkong"
              @click="deleteAll"
              style="width:72px">清空</Button>
      <div class="Drawer_shopCar"
           style="padding: 0 0 40px 0">
        <ul class="transfer-lists">
          <li class="transfer-list"
              v-for="(item, index) in this.formValidate.productList"
              :key="index">
            <span class="name"
                  style="width:70%">{{item.title}}</span>
            <span class="num"
                  style="width:40%">数量:
              <InputNumber style="width:55px;"
                           v-model="item.productQty"
                           :max="999"
                           :min="1" />
              </InputNumber></span>
            <Button class="btn-del"
                    icon="md-close"
                    type="text"
                    @click="cancelSelected(item, index)"
                    style="border:none;"></Button>
          </li>
        </ul>
      </div>
      <div class="demo-drawer-footer1 footer2">
        <Button type="default"
                @click="OK_no"
                style="width:72px">取消</Button>
        <Button type="default"
                @click="OK_again"
                style="width:72px;margin:0 20px 0 20px">继续添加</Button>
        <Button type="primary"
                @click="OK_yes"
                style="width:72px">确定</Button>
      </div>
    </Drawer>
  </div>
</template>
<script>
import { createSalesPackage, getSalesPackageList, getProductCategory, getProductQuery, setProductDel, setProductDetail, getGiftShopList } from '@/api/setting'
export default {
  data () {
    return {
      tableHeight: 0,
      isShow: false,
      isDelete: true,
      title: '',
      isDisabled: false,
      defaultUrl: require('@/assets/images/add.png'),
      // 抽屉表单
      value5: false,
      value6: false,
      value7: false,
      modal1: false,
      showSousuo: true,
      Sousuoclass: false,
      Iconclass: false,
      formValidate: {
        name: '',
        imgUrl: '',
        sousuo: '',
        cash: '',
        gender: '',
        game: '',
        status: '',
        pkgId: '', // 修改的时候需要传
        totalCount: null,
        page: null,
        productList: []
      },
      ruleValidate: {
        name: [
          { required: true, message: '水吧套餐名称不能为空', trigger: 'blur' },
          {
            required: true,
            // validator: (rule, value, callback) => {
            //   let t = value.replace(/[\u4e00-\u9fa5]/g, '')// 替换中文
            //   if ((value.length - t.length) * 2 + t.length <= 20) { // 判断长度+
            //     callback(
            //       console.log('验证成功')
            //     )
            //   } else {
            //     callback(new Error('仅支持20个汉字40个字节'))
            //   }
            // },
            trigger: 'blur'
          }
        ],
        cash: [
          { required: true, message: '现金单价不能为空', trigger: 'blur', type: 'string' }
        ],
        game: [
          { required: true, message: '游戏币购买数不能为空', type: 'string', trigger: 'blur' }
        ],
        imgUrl: [{ required: true, message: '上传图片不能为空', trigger: 'change' }],
        gender: [
          { required: true, message: '是否启用不能为空', trigger: 'change' }
        ]
        // productList: [
        //   {
        //     required: true,
        //     validator: (rule, value, callback) => {
        //       if (value.length < 1) {
        //         callback(new Error('请选择商品'))
        //       } else {
        //         callback()
        //       }
        //     },
        //     trigger: 'change'
        //   }
        // ]
      },
      // 抽屉树结构
      num: null,
      SelectClass: 'ivu-tree-title ivu-tree-title-selected',
      DefineClass: 'ivu-tree-title',
      listpage: {
        offset: 1,
        limit: 10
      },
      selectedList: [], // 存放列表数据的数组
      data: [], // 存放loding过后的子节点
      data3: [],
      data6: [],
      sousuoList: [], // 存放搜索后未点击的数组
      sousuoclickList: [], // 存放搜索后已点击的数组
      flag: true,
      attr: [], // 存放所有子节点的数组
      allNodeIds: [], // 所有节点的id集合
      attrID: [], // 存放未加载但被选中节点id的数组
      selectNodes: [], // 存放未加载但被选中节点的数组
      // 列表table
      columns7: [
        {
          title: '套餐名称',
          key: 'pkgName'
        },
        {
          title: '现金购买',
          key: 'pkgPrice',
          align: 'center'
        },
        {
          title: '游戏币购买',
          key: 'pkgCoinPrice',
          align: 'center'
        },
        {
          title: '套餐包含的商品',
          slot: 'newName'
        },
        {
          title: '是否启用',
          slot: 'status',
          align: 'center'
        },
        {
          title: '操作',
          key: 'action',
          width: 200,
          slot: 'action'
        }
      ]
    }
  },
  watch: {
    value5 (val) {
      if (!val) {
        this.$refs.formValidate.resetFields()
        this.formValidate.productList = []
        this.selectNodes = []
        this.isShow = false
        this.attrID = []
      }
    }
  },
  computed: {
  },
  created () {
  },
  mounted () {
    this.uploadList = this.$refs.upload.fileList
    this.submitForm(0, 10)
    this.getOnelei()
    if (!this.hasPermission('moms:setting:restzonepackage')) {
      this.$router.replace({ name: 'error_401' })
    }
  },
  methods: {
    deleteAll () { // 清空
      this.formValidate.productList.forEach((e) => {
        this.traverseTree(e, e.productId, true)
        this.cancelSousuo(e.productId)
        this.cancelfindNode(e.productId)
      })
      this.attrID = []
      this.selectNodes = []
      this.formValidate.productList = []
      this.num = this.formValidate.productList.length
    },
    changeprice () {
      this.changeNum()
    },
    changeNum () {
      // 如果用户第一位输入的是小数点，则重置输入框内容
      if (this.formValidate.cash !== '' && this.formValidate.cash.substring(0, 1) === '.') {
        this.formValidate.cash = ''
      }
      this.formValidate.cash = this.formValidate.cash.replace(/^0*(0\.|[1-9])/, '$1')// 粘贴不生效
      this.formValidate.cash = this.formValidate.cash.replace(/[^\d.]/g, '') // 清除“数字”和“.”以外的字符
      this.formValidate.cash = this.formValidate.cash.replace(/\.{2,}/g, '.') // 只保留第一个. 清除多余的
      this.formValidate.cash = this.formValidate.cash.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
      this.formValidate.cash = this.formValidate.cash.replace(/^(-)*(\d+)\.(\d\d).*$/, '$1$2.$3')// 只能输入两个小数
      if (this.formValidate.cash.indexOf('.') < 0 && this.formValidate.cash !== '') { // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
        if (this.formValidate.cash.substring(0, 1) === '0' && this.formValidate.cash.length === 2) {
          this.formValidate.cash = this.formValidate.cash.substring(1, this.formValidate.cash.length)
        }
      }
      if (this.formValidate.cash > 9999.99) {
        this.formValidate.cash = this.formValidate.cash.substring(0, 4)
      }
    },
    changegame () {
      this.formValidate.game = this.formValidate.game.replace(/^(0+)|[^\d]+/g, '')
    },
    priceBlur () {
      this.formValidate.cash = this.formValidate.cash + ''
      this.formValidate.cash = this.formValidate.cash.replace(/[^\d.]/g, '')
      if (this.formValidate.cash === '') {
        this.formValidate.cash = ''
      } else if (this.formValidate.cash.indexOf('.') === -1) {
        this.formValidate.cash = this.formValidate.cash + '.00'
      } else if (this.formValidate.cash.indexOf('.')) {
        let ste = this.formValidate.cash.substring(this.formValidate.cash.indexOf('.') + 1)
        if (!ste) {
          this.formValidate.cash = this.formValidate.cash + '00'
        }
        if (ste.length === 1) {
          this.formValidate.cash = this.formValidate.cash + '0'
        } if (ste.length > 2) {
          this.formValidate.cash = this.formValidate.cash.substring(0, this.formValidate.cash.indexOf('.') + 3)
        }
      }
    },
    changecoinNum () {
      this.formValidate.game = this.formValidate.game.replace(/^(0+)|[^\d]+/g, '')
    },
    keyupname () {
      this.formValidate.name = this.formValidate.name.replace(/\s+/g, '')
    },
    changeName () { // 过滤搜索空格
      this.formValidate.sousuo = this.formValidate.sousuo.replace(/\s+/g, '')
    },
    // 获取图片尺寸
    getcicun (url) {
      var img = new Image()
      img.src = url
      var _this = this
      img.onload = function () {
        if (img.width !== 235 || img.height !== 110) {
          _this.formValidate.imgUrl = ''
          _this.$Notice.warning({
            title: '上传的图片规格不符'
          })
        }
      }
    },
    handleMaxSize (file) {
      this.$Notice.warning({
        title: '上传的图片大小不能超过100k'
      })
    },
    handleFormatError (file) {
      this.$Notice.warning({
        title: '上传的图片格式错误'
      })
    },
    page_size (size) { // 选择一页加载的不同条数
      this.listpage.limit = size
      this.submitForm(0, this.listpage.limit)
    },
    sousuo (value) { // 模糊搜索
      if (value !== '') {
        getGiftShopList({
          'productName': this.formValidate.sousuo,
          'shopId': this.$route.query.id,
          'productTypeList': [11]
        }).then((res) => {
          if (res.data.status === 200) {
            this.showSousuo = false
            res.data.data.forEach((item) => {
              this.$set(item, 'Sousuoclass', false)
              let sousuoobj = {
                productId: item.productId,
                productName: item.productName,
                productSku: item.productSku,
                Sousuoclass: item.Sousuoclass,
                productQty: item.productQty
              }
              // sousuoobj.productQty = //这个 值暂定 是自己手动输入
              if (this.formValidate.productList.length === 0) { // 这个判断是 当selectedList为空的时候 就是多次搜索和多次取消的时候触发
                sousuoobj.Sousuoclass = false
              } else {
                this.formValidate.productList.forEach(ele => {
                  if (ele.productId === item.productId) {
                    item.Sousuoclass = true
                  }
                })
              }
            })
            this.sousuoList = res.data.data // 也是一直在重新的赋值 跟子节点loding一样
          } else {
            this.$Message.error('搜索失败，请联系管理员')
          }
        })
      } else {
        this.$Message.error('搜索内容不能为空')
      }
    },
    sousuo_change () { // input里面清空
      if (this.formValidate.sousuo === '') {
        this.showSousuo = true
        this.sousuoList = []
        this.sousuoclickList = []
      }
    },
    findNode (id) { // 查找指定id元素勾选
      if (this.$refs.tree.$el.querySelectorAll('.id' + id).length > 0) {
        this.$refs.tree.$el.querySelectorAll('.id' + id)[0].className = 'ivu-tree-title ivu-tree-title-selected id' + id
      }
    },
    cancelfindNode (id) { // 查找指定id元素取消勾选
      if (this.$refs.tree.$el.querySelectorAll('.id' + id).length > 0) {
        this.$refs.tree.$el.querySelectorAll('.id' + id)[0].className = 'ivu-tree-title id' + id
      }
    },
    cancelSousuo (id) { // 取消搜索时候点击的样式
      if (this.$refs.sousuoli) {
        this.$refs.sousuoli.forEach(item => {
          if (item.dataset.id === id) {
            item.className = 'sosuoli_befor'
          }
        })
      }
    },
    sousuoclickli (item, id, i) { // 搜索结果的点击
      this.sousuoList.forEach((ele, idx) => {
        if (ele.productId === item.productId) {
          if (item.Sousuoclass) {
            this.sousuoList[idx].Sousuoclass = false
            this.$refs.sousuoli[i].className = 'sosuoli_befor'
            this.Iconclass = false
            this.$refs.Iconclass[i].className = 'Icon_befor'
            if (this.sousuoclickList.length > 0) { // 查询搜索选中的数组里面的点击是否取消 取消的话就在数组里面删除这一项
              this.sousuoclickList.forEach((val, index) => {
                if (val.productId === id) {
                  this.sousuoclickList.splice(index, 1)
                }
              })
            }
            if (this.attrID.length > 0) { // 点击取消的时候 删除一个attrID里面的id
              this.attrID.forEach((it, i) => {
                if (it === id) {
                  this.attrID.splice(i, 1)
                }
              })
            }
            this.formValidate.productList.forEach((item, idx) => {
              if (item.productId === id) {
                this.traverseTree(this.formValidate.productList[idx], item.id, true)
                this.selectNodes.splice(idx, 1)
                this.cancelfindNode(id)
                this.formValidate.productList.splice(idx, 1)
                // this.OnSelect(this.selectedList[idx]) // 这个东西有问题 这个搞的selectedList里面的数据不对
                this.num = this.formValidate.productList.length
                return false
              }
            })
          } else {
            this.sousuoList[idx].Sousuoclass = true
            this.$refs.sousuoli[i].className = 'sosuoli_after'
            this.sousuoclickList.push(this.sousuoList[i]) // 被点击过的数据 存在点击后的数组
            // console.log(this.sousuoclickList, '存放搜索已点击的数据')
            // 如果已加载选中的节点  则去修改selected 修改样式  并放入selectedList
            if (this.allNodeIds.indexOf(id) !== -1) {
              // console.log('已经loding')
              this.attr.forEach(it => {
                if (it.productId === id) {
                  this.findNode(id)
                  it.selected = true
                  this.OnSelect(it)
                }
                // console.log(this.attr)
              })
            } else {
              // 如果未加载选中节点  则新增一条数据放在selectNodes 并往未加载数组中放入id 更新selectedList
              if (this.attrID.indexOf(this.sousuoList[i].productId) === -1) {
                this.attrID.push(this.sousuoList[i].productId)
              }
              // console.log(this.attrID, '存放未加载但被选中的节点id的数组')
              let obj1 = {
                title: this.sousuoList[i].productName,
                productId: this.sousuoList[i].productId,
                productSku: this.sousuoList[i].productSku,
                productQty: this.sousuoList[i].productQty,
                isSun: true,
                selected: true
              }
              this.selectNodes.push(obj1)
              this.OnSelect(obj1)
            }
            this.num = this.formValidate.productList.length
          }
        }
      })
    },
    loadData (item, callback) { // 树的loding
      setTimeout(() => {
        getProductQuery({
          'categoryId': item.categoryId,
          'productType': '11',
          'shopId': this.$route.query.id
        }).then((res) => {
          if (res.data.status === 200) {
            let list1 = []
            res.data.data.map((item) => {
              let obj1 = {
                title: item.productName,
                productId: item.productId,
                productSku: item.productSku,
                productQty: item.productQty,
                isSun: true
              }
              if (this.attrID.indexOf(item.productId) !== -1) { // 如果在未加载但选中数组中有这个id  则应默认选中
                obj1.selected = true
                this.attrID.splice(this.attrID.indexOf(item.productId), 1)
                this.selectNodes.splice(this.attrID.indexOf(item.productId), 1)
              }
              list1.push(obj1)
              this.attr.push(obj1)
              this.allNodeIds.push(item.productId)
            })
            this.data = list1
            callback(this.data)
          } else {
            this.$Message.error(`${res.data.error}`)
          }
        })
      }, 1000)
    },
    remove (row, index) { // 确定删除的回调
      if (this.isDelete) {
        if (!this.isDelete) {
          return
        }
        this.isDelete = false
        if (this.$refs.pages.currentPage !== 1) {
          if (this.formValidate.totalCount % this.listpage.limit === 1) {
            this.$refs.pages.currentPage = this.$refs.pages.currentPage - 1
          }
        }
        setTimeout(() => {
          setProductDel({
            'pkgId': row.pkgId,
            'shopId': this.$route.query.id,
            'merchantId': this.$store.state.user.merchantId
          }).then((res) => {
            this.isDelete = true
            if (res.data.status === 200) {
              this.submitForm((this.$refs.pages.currentPage - 1) * this.listpage.limit, this.listpage.limit)
              this.$Message.success('删除成功')
            } else {
              this.$Message.error(`${res.data.error}`)
            }
          })
        }, 200)
      }
    },
    cancel () { // 取消删除的回调
      // console.log('取消的回调')
    },
    uptShow (row) { // 编辑
      this.title = '编辑水吧套餐'
      this.formValidate.productList = []
      this.attrID = []
      this.selectNodes = []
      this.showSousuo = true
      this.formValidate.sousuo = '' // 清空搜索的内容 影藏掉
      this.getOnelei() // 接着调用一下loding的方法
      setProductDetail({
        'pkgCode': row.pkgCode,
        'shopId': this.$route.query.id,
        'merchantId': this.$store.state.user.merchantId
      }).then((res) => {
        if (res.data.status === 200) {
          this.flag = false
          this.formValidate.name = res.data.data.pkgName
          this.formValidate.cash = res.data.data.pkgPrice + ''
          this.formValidate.game = res.data.data.pkgCoinPrice + ''
          this.formValidate.gender = res.data.data.status + ''
          this.formValidate.status = res.data.data.status + ''
          this.formValidate.pkgId = res.data.data.pkgId
          this.formValidate.imgUrl = res.data.data.pkgImage
          this.value5 = true

          res.data.data.infos.forEach((item) => { // 编辑的时候的渲染
            if (this.attrID.indexOf(item.productId) === -1) {
              this.attrID.push(item.productId)
            }
            let obj1 = {
              title: item.productName,
              productId: item.productId,
              productSku: item.productSku,
              productQty: item.productQty,
              isSun: true,
              selected: true
            }
            this.formValidate.productList.push(obj1)
            this.selectNodes.push(obj1)
            // this.OnSelect(obj1)
          })
          this.num = this.formValidate.productList.length
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    // 上传
    handleSuccess (response, file, fileList) {
      this.formValidate.imgUrl = response.full_img_url
      // console.log(this.formValidate.imgUrl)
      this.getcicun(this.formValidate.imgUrl)
    },
    // 树结构
    cancelSelected (item, index) { // 删除列表
      this.traverseTree(this.formValidate.productList[index], item.productId, true)
      this.formValidate.productList.splice(index, 1)
      this.attrID.splice(index, 1)
      this.selectNodes.forEach((it, i) => {
        if (item.productId === it.productId) {
          this.cancelSousuo(item.productId)
          this.selectNodes.splice(i, 1)
        }
      })
      if (this.$refs.tree.$el.querySelectorAll('.ivu-tree-title-selected')[index]) {
        this.$refs.tree.$el.querySelectorAll('.ivu-tree-title-selected')[index].className = 'ivu-tree-title id' + item.productId
      }
      this.cancelSousuo(item.productId)
      this.num = this.formValidate.productList.length
    },
    traverseTree (node, id, isDel) { // 渲染列表
      if (!node) {
        return
      }
      if (node.productId === id) {
        if (isDel) {
          node.selected = false
        } else {
          node.selected = true
        }
      }
      let children = node.children
      if (children && children.length > 0) {
        for (let i = 0, l = children.length; i < l; i++) {
          this.traverseTree(children[i], id, isDel)
        }
      }
    },
    renderContent (h, { root, node, data }) { // 选中子节点赋class
      if (node.node.selected) { // 父节点收起来
        return h('span', {
          class: ['ivu-tree-title', 'ivu-tree-title-selected', 'id' + data.productId],
          on: {
            click: (e) => {
              let sun = data.isSun
              if (sun) {
                let thisClassName = e.target.className
                let parentClassName = e.target.parentNode.className
                if (thisClassName === this.SelectClass + ' id' + data.productId || parentClassName === this.SelectClass + ' id' + data.productId) {
                  node.node.selected = false
                  if (thisClassName === this.SelectClass + ' id' + data.productId) {
                    e.target.className = this.DefineClass + ' id' + data.productId
                  } else {
                    e.target.parentNode.className = this.DefineClass + ' id' + data.productId
                  }
                } else {
                  node.node.selected = true
                  if (thisClassName === this.DefineClass + ' id' + data.productId) {
                    e.target.className = this.SelectClass + ' id' + data.productId
                  } else {
                    e.target.parentNode.className = this.SelectClass + ' id' + data.productId
                  }
                }
                this.OnSelect(node)
              }
              this.num = this.formValidate.productList.length
            }
          }
        },
        [
          h('div', { style: { width: '200px', display: 'inline-block' } }, data.title),
          h('Icon', {
            props: {
              type: 'md-checkmark'
            },
            style: { // 修改对号的样式
              // marginLeft: '100px',
              color: '#2D8CF0'
            }
          })
        ])
      } else {
        return h('span', {
          class: ['ivu-tree-title', 'id' + data.productId],
          on: {
            click: (e) => {
              let sun = data.isSun
              if (sun) {
                let thisClassName = e.target.className
                let parentClassName = e.target.parentNode.className
                if (thisClassName === this.SelectClass + ' id' + data.productId || parentClassName === this.SelectClass + ' id' + data.productId) {
                  node.node.selected = false
                  if (thisClassName === this.SelectClass + ' id' + data.productId) {
                    e.target.className = this.DefineClass + ' id' + data.productId
                  } else {
                    e.target.parentNode.className = this.DefineClass + ' id' + data.productId
                  }
                } else {
                  node.node.selected = true
                  if (thisClassName === this.DefineClass + ' id' + data.productId) {
                    e.target.className = this.SelectClass + ' id' + data.productId
                  } else {
                    e.target.parentNode.className = this.SelectClass + ' id' + data.productId
                  }
                }
                this.OnSelect(node)
              }
              this.num = this.formValidate.productList.length
            }
          }
        },
        [
          h('div', { style: { width: '200px', display: 'inline-block' } }, data.title),
          h('Icon', {
            props: {
              type: 'md-checkmark'
            },
            style: { // 修改对号的样式
              // marginLeft: '100px',
              color: '#2D8CF0'
            }
          })
        ])
      }
    },
    OnSelect (data) { // 点击产品 渲染列表
      // this.$emit('OnSelectChange', data)
      if (data.node) {
        if (data.node.selected) {
          if (!data.node.productQty) {
            data.node.productQty = 1
          }
          this.formValidate.productList.push({ ...data.node })
        } else {
          this.formValidate.productList = this.formValidate.productList.filter(item => item.productId !== data.node.productId)
        }
      } else if (data.selected) {
        if (!data.productQty) {
          data.productQty = 1
        }
        this.formValidate.productList.push({ ...data })
      }
    },
    submitForm (offset, limit) {
      this.tableHeight = 0
      getSalesPackageList({ // 初始化获取列表
        'merchantId': this.$store.state.user.merchantId,
        'shopId': this.$route.query.id,
        'pkgTypes': '2',
        'offset': offset,
        'limit': limit
      }).then((res) => {
        if (res.data.status === 200) {
          res.data.data.forEach((item) => {
            item.newName = ''
            item.infos.forEach(it => {
              item.newName = item.newName + it.productName + '||'
            })
            item.newName = item.newName.substring(0, item.newName.length - 2)
            if (item.status === 0) {
              item.status = '否'
            } else {
              item.status = '是'
            }
          })
          this.formValidate.totalCount = res.data.totalCount
          this.data6 = res.data.data
          if (res.data.data && res.data.data.length >= 10) {
            this.tableHeight = 520
          }
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    getOnelei () {
      getProductCategory({ // 获取的一级分类(零食 饮料)
        'merchantId': this.$store.state.user.merchantId,
        'shopId': this.$route.query.id,
        'categoryType': '0',
        'parentId': '0'
      }).then((res) => {
        if (res.data.status === 200) {
          let list = []
          res.data.data.map((item) => {
            let obj = {}
            obj.title = item.categoryName
            obj.categoryId = item.categoryId
            obj.loading = false
            obj.children = []
            list.push(obj)
          })
          this.data3 = list
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    Radio_change (e) {
      this.formValidate.status = e
      // console.log(this.formValidate.status)
    },
    handleSubmit (name) { // 保存
      this.isShow = true
      this.$refs[name].validate((valid) => {
        if (valid) {
          if (this.formValidate.productList.length > 0) {
            if (this.flag) { // 点击新增进入
              this.formValidate.pkgId = ''
              let list2 = []
              this.formValidate.productList.map((item) => {
                let obj2 = {
                  productName: item.title,
                  productId: item.productId,
                  productSku: item.productSku
                }
                if (item.productQty) {
                  obj2.productQty = item.productQty
                } else {
                  obj2.productQty = '1'
                }
                list2.push(obj2)
              })
              if (this.isDisabled) {
                return
              }
              this.isDisabled = true
              createSalesPackage({
                'pkgName': this.formValidate.name,
                'pkgPrice': this.formValidate.cash,
                'pkgCoinPrice': this.formValidate.game,
                'pkgType': '2', // 2代表水吧套餐
                'status': this.formValidate.status, // 0 不启用 1启用
                'items': list2,
                'pkgImage': this.formValidate.imgUrl,
                'creator': 'szd',
                'shopId': this.$route.query.id,
                'merchantId': this.$store.state.user.merchantId
              }).then((res) => {
                this.isDisabled = false
                if (res.data.status === 200) {
                  this.$Message.success('添加成功')
                  this.$refs.pages.currentPage = 1
                  this.submitForm(0, this.listpage.limit)
                  this.value5 = false
                } else {
                  this.$Message.error(`${res.data.error}`)
                }
              })
            } else { // 点击编辑进入
              let list2 = []
              this.formValidate.productList.map((item) => {
                let obj2 = {}
                obj2.productName = item.title
                obj2.productId = item.productId
                obj2.productSku = item.productSku
                if (item.productQty) {
                  obj2.productQty = item.productQty
                } else {
                  obj2.productQty = '1'
                }
                list2.push(obj2)
              })
              if (this.isDisabled) {
                return
              }
              this.isDisabled = true
              createSalesPackage({
                'pkgId': this.formValidate.pkgId,
                'pkgName': this.formValidate.name,
                'pkgPrice': this.formValidate.cash,
                'pkgCoinPrice': this.formValidate.game,
                'pkgType': '2', // 2代表水吧套餐
                'status': this.formValidate.status, // 0 不启用 1启用
                'items': list2,
                'pkgImage': this.formValidate.imgUrl,
                'creator': 'szd',
                'shopId': this.$route.query.id,
                'merchantId': this.$store.state.user.merchantId
              }).then((res) => {
                this.isDisabled = false
                if (res.data.status === 200) {
                  this.$Message.success('修改成功')
                  this.$refs.pages.currentPage = 1
                  this.submitForm(0, this.listpage.limit)
                  this.value5 = false
                } else {
                  this.$Message.error(`${res.data.error}`)
                }
              })
            }
          }
        }
      })
    },
    handleReset (name) {
      this.$refs[name].resetFields()
      this.value5 = false
      this.isShow = false
    },
    add () {
      this.formValidate.imgUrl = false
      this.title = '添加水吧套餐'
      this.showSousuo = true
      this.selectNodes = []
      this.formValidate.sousuo = '' // 清空搜索的内容 影藏掉
      this.formValidate.productList = [] // 添加的时候清空数组
      this.getOnelei() // 接着调用一下loding的方法
      this.num = 0
      this.flag = true
      this.formValidate.name = ''
      this.formValidate.cash = ''
      this.formValidate.game = ''
      this.formValidate.gender = ''
      this.formValidate.pkgId = ''
      this.value5 = true
    },
    pageNum (page) {
      this.page = page
      this.submitForm((page - 1) * this.listpage.limit, this.listpage.limit)
    },
    // 添加页面按钮
    add_no () {
      this.value6 = false
    },
    // 点击取消按钮
    cancelSelect () {
      this.value6 = false
      this.formValidate.productList = []
      this.selectNodes = []
      this.attrID = []
      this.num = null
      this.sousuoList = []
      this.formValidate.sousuo = ''
      this.showSousuo = true
      this.getOnelei()
    },
    yes () {
      this.value7 = true
      this.num = this.formValidate.productList.length
    },

    // 完成添加按钮
    OK_no () {
      this.value7 = false
    },
    OK_yes () {
      this.value7 = false
    },
    OK_again () {
      this.value7 = false
    }
  }
}
</script>
<style lang="less" scoped>
#water-bal-meal {
  .Col_right {
    .Col_right_list {
      .content_page {
        padding: 20px;
        display: flex;
        flex-direction: row;
        justify-content: flex-end;
        .page {
          margin-left: 2%;
        }
      }
    }
  }
}
</style>
<style lang="less">
#water-bal-meal {
  .demo-drawer-footer1 {
    // width: 540px;
    position: fixed;
    bottom: 0;
    right: 0;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: right;
    background: #fff;
  }
  .footer1 {
    width: 540px;
  }
  .footer2 {
    width: 360px;
  }
  .ivu-drawer-content {
    .qingkong {
      position: fixed;
      top: 9.5px;
      right: 20px;
    }
  }
  .transfer-list {
    display: flex;
    justify-content: space-between;
    height: 45px;
    line-height: 45px;
  }
  .grid_btn {
    border: none;
    width: 20px;
    // margin-left: 20px;
    padding: 0 10px;
    font-size: 15px;
    background-color: #fff;
    outline: 0 none !important;
    cursor: pointer;
  }
  .ivu-upload {
    width: 96px;
    height: 96px;
    position: relative;
    .replace_tit {
      position: absolute;
      bottom: 0;
      width: 96px;
      opacity: 0.6;
      background: #2d8cf0;
      height: 24px;
      text-align: center;
      line-height: 24px;
      font-size: 12px;
      color: #ffffff;
      display: none;
    }
  }
  .Drawer_Tree {
    padding: 0 0 40px 0;
    .ivu-tree-title-selected,
    .ivu-tree-title-selected:hover,
    .ivu-tree-title:hover {
      background-color: #ffffff;
    }
    .sosuoli_befor {
      margin-bottom: 5px;
      margin-top: 5px;
      cursor: pointer;
      .Icon_befor {
        color: #fff;
        // margin-left: 80px;
      }
    }
    .sosuoli_after {
      margin-top: 5px;
      margin-bottom: 5px;
      color: #2d8cf0;
      cursor: pointer;
      .Icon_befor {
        color: #2d8cf0;
        // margin-left: 100px;
      }
    }
    .ivu-tree-title {
      // 默认的样式
      vertical-align: middle;
      span {
        margin: 0 10px;
      }
      .ivu-icon {
        //前面图标的样式
        color: red;
        margin-left: 20px;
        font-size: 16px;
        &.ivu-icon-md-checkmark {
          display: none;
        }
      }
      &.ivu-tree-title-selected {
        // 点击过后的样式 title的样式
        color: #2d8cf0;
        .ivu-icon {
          &.ivu-icon-md-checkmark {
            display: inline-block;
            color: #19be6b;
          }
        }
      }
    }
  }
  .btn-del .ivu-btn .ivu-btn-text .ivu-btn-icon-only {
    border: none;
    outline: 0 none !important;
  }

  .Tree_button {
    width: 100%;
    display: flex;
    flex-direction: row;
    justify-content: flex-end;
    position: absolute;
    bottom: 0;
    left: 0;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: right;
    background: #fff;
  }
  .set_ct_form_up .ivu-form-item-content {
    display: flex;
  }
  .set_ct_form_name .ivu-form-item-label::before {
    display: none;
  }
}
</style>
